package com.yuwenchao.superafflatus.controller;

import com.yuwenchao.superafflatus.constant.AfflatusConstant;
import com.yuwenchao.superafflatus.service.SuperSalaryService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;


/**
 * @author chaooGG
 * @version 1.0
 * @date 2021/7/30 10:15
 *
 *   不管是什么环境都可以下载项目路径下文件的方法
 *   以后springboot项目路径下文件下载建议使用该方法
 *   该方法打包后下载项目下路径不会报错
 */
@Slf4j
@Api(tags = "springboot项目路径文件下载")
@Controller
public class SpringbootNativeDownController {


    @Value("${linuxFile.ExcelModel}")
    private String ExcelModel;

    @Value("${linuxFile.DownCalc}")
    private String DownCalc;



    @Autowired
    SuperSalaryService salaryService;
    /**
     * 下载文件
     * @param fileName 下载文件名称
     * @param response 响应
     * @throws IOException 异常
     */
    public static void downFile(String fileName, HttpServletRequest request,
                                HttpServletResponse response, InputStream in) throws IOException {
        //输出流自动关闭，java1.7新特性
        try(OutputStream os = response.getOutputStream()) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
            response.reset();
            response.setHeader("Content-Disposition", "attachment; filename=" + fileName);
            response.setContentType("application/octet-stream; charset=UTF-8");
            byte[] b = new byte[in.available()];
            in.read(b);
            os.write(b);
            os.flush();
        } catch (Exception e) {
            System.out.println("fileName=" + fileName);
            e.printStackTrace();
        } finally {
            if (in != null) {
                in.close();
            }
        }
    }


    @ApiOperation(value = "下载Linux文件")
    @GetMapping("/downloadLinuxFile")
    public void downloadLinuxFile(HttpServletRequest request, HttpServletResponse response){
        log.info("Linux部署文件开始下载");
        ClassPathResource resource = new ClassPathResource(AfflatusConstant.LINUX_TXT);
        try {
            //获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("linux部署文档.txt",request,response,in);
            log.info("Linux部署文件下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "下载Linux运行脚本文件")
    @GetMapping("/downloadLinuxSH")
    public void downloadLinuxSH(HttpServletRequest request, HttpServletResponse response){
        log.info("Linux运行脚本开始下载");
        ClassPathResource resource = new ClassPathResource(AfflatusConstant.LINUX_SH);
        try {
            //获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("run.sh",request,response,in);
            log.info("Linux运行脚本下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }




//该下载在项目中 会导致linux下载文件错误
    @ApiOperation(value = "下载Excel模板文件")
    @GetMapping("downloadExcelFile")
    public void downloadExcelFile(HttpServletRequest request, HttpServletResponse response){
       log.info("Excel模板文件开始下载");
        ClassPathResource resource = new ClassPathResource(AfflatusConstant.DOWNLOAD_EXCELMODEL);
        try {
            //获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("员工模板.xlsx",request,response,in);
            log.info("Excel模板文件下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //该下载在项目中 会导致linux下载文件错误
    @ApiOperation(value = "下载多功能计算器文件")
    @GetMapping("downloadCalc")
    public void downloadCalcFile(HttpServletRequest request, HttpServletResponse response){
        log.info("多功能计算器文件开始下载");
        ClassPathResource resource = new ClassPathResource(AfflatusConstant.DOWNLOAD_CALCULATOR);
        try {
            //获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("多功能理财工具.zip",request,response,in);
            log.info("多功能计算器文件下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    @ApiOperation(value = "环境通用Excel模板文件linux下载")
    @GetMapping("/downloadExcelFileCommon")
    public void downloadExcelFileCommon(HttpServletResponse response) throws IOException {
        String fileName ="model.xlsx";
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );
        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
            // FileInputStream inputStream = new FileInputStream(downloadFile+fileName);
            // 取非项目环境下的文件
            FileInputStream inputStream = new FileInputStream(ExcelModel);

            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }

    @ApiOperation(value = "环境通用多功能计算器文件下载")
    @GetMapping("/downloadCalcFileCommon")
    public void downloadCalcFile(HttpServletResponse response) throws IOException {

        String fileName ="calc.zip";
        response.setHeader( "Content-Disposition", "attachment;filename="  + new String( fileName.getBytes("gb2312"), "ISO8859-1" ) );

        if(!fileName.isEmpty()) {

            //response.addHeader("Content-Disposition", "attachment;filename=" + TxtName);
            response.setContentType("multipart/form-data");
            // FileInputStream inputStream = new FileInputStream(downloadFile+fileName);
            // 取非项目环境下的文件
            FileInputStream inputStream = new FileInputStream(DownCalc);

            ServletOutputStream stream = response.getOutputStream();
            IOUtils.copy(inputStream, stream);
            inputStream.close();
        }
    }













    @PreAuthorize("hasRole('ROLE_admin')")
    @ApiOperation(value = "下载SQL文件")
    @GetMapping("downloadSQLFile")
    public void downloadSQLFile(HttpServletRequest request, HttpServletResponse response){
        log.info("SQL文件开始下载");
        ClassPathResource resource = new ClassPathResource(AfflatusConstant.DOWNLOAD_SQLFILE);
        try {
            //获取文件输入流
            InputStream in = resource.getInputStream();
            //下载文件
            downFile("afflatus.sql",request,response,in);
            log.info("SQL文件下载完成");
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


}
